//
//  ChangeInfoViewController.m
//  金融
//
//  Created by Apple on 2017/10/27.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "ChangeInfoViewController.h"
#import "UserInfoNameCell.h"
#import "UserInfoImageCell.h"
#import "ChangePassWordViewController.h"

static NSString * cellID = @"UserInfoNameCellID";
static NSString * UsersellID = @"UserInfoImageCellID";
@interface ChangeInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSArray     * dataArray;
@end

@implementation ChangeInfoViewController

- (NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = @[@{@"title":@"头像"},@{@"title":@"名字"},@{@"title":@"修改密码"}];
    }
    return _dataArray;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"UserInfoNameCell" bundle:nil] forCellReuseIdentifier:cellID];
        [_tableView registerNib:[UINib nibWithNibName:@"UserInfoImageCell" bundle:nil] forCellReuseIdentifier:UsersellID];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"个人信息";
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom);
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 70.f;
    }
    return 50.f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserInfoNameCell * cell = (UserInfoNameCell *)[tableView dequeueReusableCellWithIdentifier:cellID];
    UserInfoImageCell * IconCell = (UserInfoImageCell *)[tableView dequeueReusableCellWithIdentifier:UsersellID];
    switch (indexPath.row) {
        case 0:
        {
            [IconCell setDataWithDict:self.dataArray[indexPath.row]];
            return IconCell;
        }
            break;
        case 1:
        {
            [cell setDataWithDict:self.dataArray[indexPath.row] isHidden:NO];
            return cell;
        }
            break;
        default:
        {
            [cell setDataWithDict:self.dataArray[indexPath.row] isHidden:YES];
            return cell;
        }
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            //按钮：从相册选择，类型：UIAlertActionStyleDefault
            [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //初始化UIImagePickerController
                UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
                //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
                //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
                PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                //允许编辑，即放大裁剪
                PickerImage.allowsEditing = YES;
                //自代理
                PickerImage.delegate = self;
                //页面跳转
                [self presentViewController:PickerImage animated:YES completion:nil];
            }]];
            //按钮：拍照，类型：UIAlertActionStyleDefault
            [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
                /**
                 其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
                 */
                UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                //获取方式:通过相机
                PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
                PickerImage.allowsEditing = YES;
                PickerImage.delegate = self;
                [self presentViewController:PickerImage animated:YES completion:nil];
            }]];
            //按钮：取消，类型：UIAlertActionStyleCancel
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
        }
            break;
        case 1:
        {
            WeakSelf
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改名字" message:@"请填写你的新名字" preferredStyle:UIAlertControllerStyleAlert];
            
            [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                textField.placeholder = @"名字";
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                UITextField *name = alertController.textFields.firstObject;
                if ([self checkWithName:name.text]) {
                    if (name.text.length > 0) {
                        [weakSelf updateToServiceName:name.text indexPath:indexPath];
                    }
                }
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
            break;
        default:
        {
            ChangePassWordViewController * cv = [[ChangePassWordViewController alloc] init];
            [self.navigationController pushViewController:cv animated:YES];
        }
            break;
    }
}
- (void)alertTextFieldDidChange:(NSNotification *)notification{
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        UITextField *name = alertController.textFields.firstObject;
        UIAlertAction *okAction = alertController.actions.lastObject;
        okAction.enabled = name.text.length >= 2;
    }
}
#pragma mark - 图片控制器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *avatar = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self updateToServiceAvatar:avatar indexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 提交服务器
- (void)updateToServiceAvatar:(UIImage *)avatar indexPath:(NSIndexPath *)indexPath
{
    WeakSelf
    NSData *data = UIImageJPEGRepresentation(avatar,1.0);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:0];
    NSString * imageStr = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",encodedImageStr];
    [HttpRequest postWithURLString:HOST(@"common/file/upload/image/base64") parameters:@{@"path":imageStr} showProgressHud:NO success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [HttpRequest postWithURLString:HOST(@"app/user/update/avatar") parameters:@{@"avatar":responseObject[@"data"][@"path"]} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
                    NSString *path_document = NSHomeDirectory();
                    //设置一个图片的存储路径
                    NSString *imagePath = [path_document stringByAppendingString:@"/Documents/icon.png"];
                    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
                    [UIImagePNGRepresentation(avatar) writeToFile:imagePath atomically:YES];
                    if (weakSelf.ClickChangeInfoBlock) {
                        weakSelf.ClickChangeInfoBlock();
                    }
                    [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                }
            } failure:^(NSError * _Nullable error) {
                
            }login:^(BOOL isLogin) {
                
            }];
        }
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    }login:^(BOOL isLogin) {
        [weakSelf PushLogin];
    }];
}

- (void)updateToServiceName:(NSString *)name indexPath:(NSIndexPath *)indexPath
{
    WeakSelf
    [HttpRequest postWithURLString:HOST(@"app/user/update/nickname") parameters:@{@"nickName":name} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [HFUser rememberNickName:name];
            if (weakSelf.ClickChangeInfoBlock) {
                weakSelf.ClickChangeInfoBlock();
            }
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    } failure:^(NSError * _Nullable error) {
        
    }login:^(BOOL isLogin) {
        
    }];
}

- (BOOL)checkWithName:(NSString *)name
{
    NSString *regex = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if(![pred evaluateWithObject: name])
    {
        /*
         ////此动画为弹出buttonqww
         UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"昵称只能由中文、字母或数字组成" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
         [alertView show];
         return;
         */

        [MyObject failedPrompt1:@"只能由中文、字母或数字组成"];
        /*
         //此动画为在顶上显示文字
         [MPNotificationView notifyWithText:@"昵称只能由中文、字母或数字组成"
         andDuration:0.5];
         */
        return NO;
    }else{
        return YES;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

